package com.github.tetrisgame.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.tetrisgame.utils.UIUtils;

//自定义组合 EditText
//继承自EditText 【1.弹出键盘 2.获取输入的内容】其余都是自定义绘制
//完全自定义【1.弹出键盘 2.获取输入的内容 3.光标闪烁 4.显示内容】
public class PhoneVerifyInputView extends View {
    //确定每个输入框的默认尺寸
    private int mSize = UIUtils.dp2px(30);
    //方格的个数
    private int mGridCount = 6;
    //文字默认尺寸
    private float mTextSize = UIUtils.sp2pxF(10);
    //文字颜色
    private int mTextColor = Color.parseColor("#3ED689");
    //方格之间的间距
    private int mGap = UIUtils.dp2px(10);
    //光标的宽度
    private float mCursorWidth = UIUtils.dp2pxF(2);
    //光标的高度
    private float mCursorHeight = 0;
    //灰色背景
    private int mGrayColor = Color.parseColor("#E5E5E5");
    //圆角半径
    private float mRadius = UIUtils.dp2pxF(10);

    //用于记录输入的内容
    private StringBuilder inputTextSB = new StringBuilder();
    //绘制文本的画笔
    private TextPaint mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    //绘制光标的画笔
    private Paint mCursorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    //方格画笔
    private Paint mGridPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    //光标是否显示
    private boolean mCursorVisible = true;
    private OnInputListener mInputListener;

    public PhoneVerifyInputView(Context context) {
        this(context,null);
    }

    public PhoneVerifyInputView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public PhoneVerifyInputView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    //初始化操作
    private void init(){
        //配置当前这个视图拥有获取焦点的能力
        setFocusable(true);
        setFocusableInTouchMode(true);
        setClickable(true);

        //文本画笔
        mTextPaint.setTextSize(TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP,
                mTextSize,
                getResources().getDisplayMetrics()));
        mTextPaint.setColor(Color.BLACK);

        //光标画笔
        mCursorPaint.setColor(mTextColor);
        mCursorPaint.setStyle(Paint.Style.FILL);

        //计算光标的高度
        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        mCursorHeight = fontMetrics.descent - fontMetrics.ascent;
    }

    //设置键盘类型
    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        //配置弹出的键盘是用于输入手机号的
        outAttrs.inputType = EditorInfo.TYPE_CLASS_NUMBER;
        //配置键盘的回车键显示的内容
        outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
        return new BaseInputConnection(this,false);
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        if (event.getAction() == MotionEvent.ACTION_DOWN){
//            //弹出键盘 键盘属于系统，通过获取系统的服务拿到
//            requestFocus();
//            InputMethodManager imm = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.showSoftInput(this,InputMethodManager.SHOW_IMPLICIT);
//        }
//        return true;
//    }


    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        postDelayed(()->{
            //弹出键盘 键盘属于系统，通过获取系统的服务拿到
            requestFocus();
            InputMethodManager imm = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(this,InputMethodManager.SHOW_IMPLICIT);
        },200);
    }

    /**
     * @param keyCode a key code that represents the button pressed, from
     *                {@link android.view.KeyEvent}
     * @param event the KeyEvent object that defines the button action
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //过滤数字
        if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9){
            if (inputTextSB.length() < mGridCount) {
                //将数字编码转化为对应的数字字符串 KEYCODE_0  -> "0“
                inputTextSB.append((char) event.getUnicodeChar());
                //重绘
                invalidate();

                //判断输入是否完毕
                if (inputTextSB.length() == mGridCount){
                    if (mInputListener != null){
                        mInputListener.onInput(inputTextSB.toString());
                    }
                }
            }
        }

        //删除键
        if (keyCode == KeyEvent.KEYCODE_DEL){
            if (inputTextSB.length() > 0){
                inputTextSB.deleteCharAt(inputTextSB.length()-1);
                invalidate();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //开启一个定时任务，让光标闪烁
        startBlinkCursor();
    }

    private void startBlinkCursor(){
        post(()->{
            mCursorVisible = !mCursorVisible;
            postInvalidate();
            postDelayed(this::startBlinkCursor,500);
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //自己确定尺寸  根据外部尺寸去计算
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        if (widthMode == MeasureSpec.EXACTLY){
            //外部设定的精确值
            mSize = (widthSize - (mGridCount+1)*mGap)/mGridCount;
        }

        setMeasuredDimension(mSize*mGridCount + (mGridCount+1)*mGap,mSize + 2*mGap);
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        //绘制方格
        drawGrid(canvas);
        //绘制光标
        drawCursor(canvas);
        //绘制文本
        drawText(canvas);
    }
    //绘制文本
    private void drawText(Canvas canvas) {
        for (int i = 0; i < inputTextSB.length(); i++) {
            //获取i对应的数字
            String text = inputTextSB.charAt(i)+"";
            //获取文本的宽度
            float textWidth = mTextPaint.measureText(text);
            //计算文本对应的x便宜量
            float x = mGap + (mSize - textWidth) / 2 + i * (mSize + mGap);
            //计算y坐标
            Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
            float y = getHeight() / 2f - (fontMetrics.bottom+fontMetrics.top)/2;
            canvas.drawText(text,x,y,mTextPaint);
        }
    }

    //绘制光标
    private void drawCursor(Canvas canvas) {
        if (mCursorVisible) {
            if (inputTextSB.length() < mGridCount) {
                int cursorIndex = inputTextSB.length();
                float left = mGap + (mSize - mCursorWidth) / 2 + cursorIndex * (mSize + mGap);
                float top = (getHeight() - mCursorHeight) / 2;
                float right = left + mCursorWidth;
                float bottom = top + mCursorHeight;
                canvas.drawRect(left, top, right, bottom, mCursorPaint);
            }
        }
    }

    //绘制方格
    private void drawGrid(Canvas canvas){
        int cursorIndex = inputTextSB.length();

        //绘制灰色方格
        mGridPaint.setColor(mGrayColor);
        mGridPaint.setStyle(Paint.Style.FILL);
        for (int i = 0; i < mGridCount; i++) {
            //正在输入的方格不需要绘制灰色区域
            if (i == cursorIndex) continue;

            canvas.drawRoundRect(
                    mGap+i*(mSize+mGap),
                    mGap,
                    mGap+i*(mSize+mGap)+mSize,
                    mGap+mSize,
                    mRadius,
                    mRadius,
                    mGridPaint
            );
        }

        //绘制当前的正在接收输入的方格
        if (cursorIndex < mGridCount) {
            mGridPaint.setColor(mTextColor);
            mGridPaint.setStyle(Paint.Style.STROKE);
            mGridPaint.setStrokeWidth(UIUtils.dp2px(1));
            canvas.drawRoundRect(
                    mGap + cursorIndex * (mSize + mGap),
                    mGap,
                    mGap + cursorIndex * (mSize + mGap) + mSize,
                    mGap + mSize,
                    mRadius,
                    mRadius,
                    mGridPaint
            );
        }
    }

    //清空内容
    public void clear(){
        inputTextSB.setLength(0);
        invalidate();
    }

    public void setOnInputListener(OnInputListener listener){
        this.mInputListener = listener;
    }
    //输入数据回调的监听器
    public interface OnInputListener{
        void onInput(String inputText);
    }
}
